from flask import Blueprint, render_template, request, redirect, url_for, session
import json
import pymysql
from config import Config
lg = Blueprint('lg', __name__)
# 1
'''
返回管理员登陆页
'''
@lg.route('/login', methods=['POST', 'GET'])
def login():

    # GET请求返回登陆页面
    if request.method == 'GET':
        return render_template('login.html')
    '''
    登录验证
    设置两个session
    是否已登录 login 已登录 success 未登录 fail
    权限 power 超级管理员 2 管理员 1 普通用户 0 冻结用户 -1
    '''
    if request.method == 'POST':
        connect = pymysql.connect(host=Config.MYSQL_HOST, user=Config.MYSQL_USER, passwd=Config.MYSQL_PASSWD,
                                  port=Config.MYSQL_PORT, database=Config.MYSQL_DATABASE)
        cursor = connect.cursor()
        data = json.loads(request.data.decode())
        # 获取账号密码
        user_id = data['user_id']
        password = data['password']

        # rows = db.session.query(User.user_id, User.power, User.user_name).\
        #     filter(and_(User.password == password, User.user_id == user_id)).all()
        cursor.execute('select user_id,power,user_name from user where password = %s and user_id = %s;',
                       (password, user_id))
        rows = cursor.fetchall()
        # 账号存在
        if len(rows) > 0:
            session["user_id"] = rows[0][0]
            session['login'] = 'success'
            # 判断是否为管理员
            power = rows[0][1]
            session['power'] = int(power)
            session['user_name'] = rows[0][2]
            if power == -1:
                return 'dj'
            elif power == 2:
                return 'root'
            else:
                return 'success'
        # 账号不存在
        else:
            session['login'] = 'fail'
            return 'fail'

@lg.route('/exit')
def exit():
    session.clear()
    session['login'] = 'fail'
    session['power'] = -404
    return render_template('login.html')